from datetime import date, datetime
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.future import select
from .models import E2Img, E2Pat
from pydantic import BaseModel
from sqlalchemy.orm import Session
from .database import SessionLocal, engine
from . import models
from typing import List

app = FastAPI()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@app.get("/")
async def read_root():
    return {"message": "Welcome to FastAPI with PostgreSQL!"}

class E2ImgOut(BaseModel):
    img_id: int	
    img_filename: str | None
    img_modality: str | None
    img_mode: str | None
    img_acquisition_datetime: datetime | None
    img_imported: bool | None
    img_kvp: float | None
    img_ma: float | None
    img_dose: float | None
    img_note: str | None
    pat_id: int | None
    pat_chartno: str | None
    img_raw_filename: str | None
    img_update_datetime: datetime | None
    img_modelname: str | None
    img_study_instance_uid: str | None
    rec_id: int | None
    img_exposure_time: float | None
    img_comments: str | None
    img_source_type: str | None
    img_source_id: str | None
    img_user_defined_1: int | None
    img_user_defined_2: int | None
    img_user_defined_3: int | None
    img_user_defined_4: float | None
    img_user_defined_5: float | None
    img_user_defined_6: bool | None
    img_user_defined_7: bool | None
    img_user_defined_8: bool | None
    img_user_defined_9: str | None
    img_user_defined_10: str | None
    img_user_defined_11: str | None
    img_user_defined_12: str | None
    to_sended: bool | None

# @app.post("/E2Img/", response_model=E2Img)
# async def create_E2Img(E2Img: E2Img, db: Session = Depends(get_db)) -> E2ImgOut:
#     db.add(E2Img)
#     await db.commit()
#     await db.refresh(E2Img)
#     return E2Img


@app.get("/get_E2Img/", response_model=list[E2ImgOut])
def get_E2Img(db: Session = Depends(get_db)) -> list[E2ImgOut]:
    result = db.query(models.E2Img)
    print(result.all())
    return result.all()


class E2PatOut(BaseModel):
    pat_id: int
    pat_chartno: str | None
    pat_lastname: str | None
    pat_firstname: str | None
    pat_middlename: str | None
    pat_gender: str | None
    pat_birthdate: date | None
    pat_email: str | None
    pat_socialid: str | None
    pat_registered_datetime: datetime | None
    pat_photo_filename: str | None
    pat_chosung: str | None
    pat_note: str | None
    pat_phone: str | None
    pat_zipcode: str | None
    pat_address: str | None
    pat_mobile: str | None
    pat_source_type: str | None
    pat_source_id: str | None
    pat_last_access: datetime | None
    pat_user_defined_1: int | None
    pat_user_defined_2: int | None
    pat_user_defined_3: float | None
    pat_user_defined_4: float | None
    pat_user_defined_5: bool | None
    pat_user_defined_6: bool | None
    pat_user_defined_7: str | None
    pat_user_defined_8: str | None
    pat_user_defined_9: str | None
    pat_user_defined_10: str | None
    
@app.get("/get_E2Pat/", response_model=list[E2PatOut])
def get_E2Pat(db: Session = Depends(get_db)) -> list[E2PatOut]:
    result = db.query(models.E2Pat)
    print(result.all())
    return result.all()
    
    
class E2Shots(BaseModel):
    pat_id: int
    pat_chartno: str  | None
    pat_lastname: str  | None
    pat_firstname: str  | None
    pat_gender: str  | None
    pat_birthdate: date  | None
    pat_phone: str  | None
    pat_address: str  | None
    img_filename: str  | None
    tooth_code: str  | None
    img_acquisition_datetime: datetime  | None
@app.get("/get_shots/")
def get_shots(db: Session = Depends(get_db)) -> list[E2Shots]:
    result = db.query(
        E2Img.pat_id,
        E2Img.pat_chartno,
        E2Pat.pat_lastname,
        E2Pat.pat_firstname,
        E2Pat.pat_gender,
        E2Pat.pat_birthdate,
        E2Pat.pat_phone,
        E2Pat.pat_address,
        E2Img.img_filename,
        E2Img.img_mode.label('tooth_code'),
        E2Img.img_acquisition_datetime
    ).join(E2Pat, E2Pat.pat_id == E2Img.pat_id)
    print(result.all())
    return result.all()
# @app.get("/E2Pat/{pat_id}", response_model=E2Pat)
# async def read_E2Pat(pat_id: int, db: AsyncSession = Depends(get_db)):
#     result = await db.execute(select(E2Pat).filter(E2Pat.pat_id == pat_id))
#     E2Pat = result.scalar_one_or_none()
#     if E2Pat is None:
#         raise HTTPException(status_code=404, detail="Patient not found")
#     return E2Pat

# Инициализация базы данных